using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using WhittleList.Helpers;
using WhittleList.Bll;
using WhittleList.Bll.Exceptions;

namespace WhittleList.Controllers
{
    //[Authorize]
    public class SiteController : BaseController
    {
        public SiteController() : this(new UserRepository(), new SiteRepository())
        {
        }

        public SiteController(IUserRepository userRepository, ISiteRepository siteRepository) : base(userRepository, siteRepository)
        {
        }

        //
        // GET: /Site/

        public ActionResult Index()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(string name, string url)
        {
            var site = new Site();
            site.Name = name;
            site.Url = url;
            site.OwnerId = CurrentUser.Id;
            SiteRepository.Insert(site);
            try
            {
                SiteRepository.SaveChanges(CurrentUser);
            }
            catch (ValidationException)
            {
                this.ModelState.AddModelErrors(site.GetRuleViolations());
            }
            catch (DuplicateNameException e)
            {
                this.ModelState.AddModelError("Name", e);
            }
            catch (DuplicateUrlException e)
            {
                this.ModelState.AddModelError("Url", e);
            }

            if (!ModelState.IsValid)
            {
                return View(site);
            }
            else
            {
                return Redirect(Url.Dashboard(site));
            }
        }



        
    }
}
